package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;


    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
//        计算返回日期集合字符串
        List<LocalDate> localDates = new ArrayList<>();
        while (!begin.equals(end)) {
            localDates.add(begin);
            begin = begin.plusDays(1);
        }
        localDates.add(end);
        String dateList = StringUtils.join(localDates, ",");
//查询营业额数据并转为字符串
        List<Double> amountList = new ArrayList<>();
        for (LocalDate date : localDates) {
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);

//            查询date日期对应的营业额，订单状态为已完成
            Map map = new HashMap<>();
            map.put("begin", min);
            map.put("end", max);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            amountList.add(turnover);
        }
        String turnoverList = StringUtils.join(amountList, ",");
        TurnoverReportVO vo = TurnoverReportVO.builder().dateList(dateList).turnoverList(turnoverList).build();

        return vo;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //        计算返回日期集合字符串
        List<LocalDate> localDates = new ArrayList<>();


        while (!begin.equals(end)) {
            localDates.add(begin);
            begin = begin.plusDays(1);

        }
        localDates.add(end);


        String dateList = StringUtils.join(localDates, ",");


        //查询用户总数集合并转为字符串
        List<Integer> newUserNumberList = new ArrayList<>();
        List<Integer> totalUserNumberList = new ArrayList<>();
        for (LocalDate date : localDates) {
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);

//            查询date日期对应的营业额，订单状态为已完成
            Map map = new HashMap<>();
            map.put("end", max);
//总用户数
            Integer total = userMapper.countByMap(map);
            total = total == null ? 0 : total;
            totalUserNumberList.add(total);

//            新增用户数

            map.put("begin", min);
            Integer newUser = userMapper.countByMap(map);

            newUser = newUser == null ? 0 : newUser;
            newUserNumberList.add(newUser);
        }
        String newUserList = StringUtils.join(newUserNumberList, ",");
        String totalUserList = StringUtils.join(totalUserNumberList, ",");

        UserReportVO vo = UserReportVO.builder().dateList(dateList).newUserList(newUserList).totalUserList(totalUserList).build();
        return vo;
    }


    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //        订单总数、有效订单数和订单有效率


        //        计算返回日期集合字符串
        List<LocalDate> localDates = new ArrayList<>();
        while (!begin.equals(end)) {
            localDates.add(begin);
            begin = begin.plusDays(1);

        }
        localDates.add(end);
        String dateList = StringUtils.join(localDates, ",");

//      订单数列表，以逗号分隔
        List<Integer> orderCountList = new ArrayList<>();
//        有效订单数列表，以逗号分隔
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : localDates) {

            Integer orderCount = getOrderCount(date, date, null);
//          查询date日期对应订单，状态为已完成
            Integer validOrderCount = getOrderCount(date, date, Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);

        }
        String orderCountListStr = StringUtils.join(orderCountList, ",");
        String validOrderCountListStr = StringUtils.join(validOrderCountList, ",");

//        Integer totalOrderCount = getOrderCount(begin, end, null);
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
//        有效订单数
//        Integer validOrderTotalCount = getOrderCount(begin, end, Orders.COMPLETED);
        Integer validOrderTotalCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0)
            orderCompletionRate = validOrderTotalCount.doubleValue() / totalOrderCount.doubleValue();


        return new OrderReportVO().builder()
                .dateList(dateList)
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(orderCountListStr)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderTotalCount)
                .validOrderCountList(validOrderCountListStr).build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

//        获取销量前十的菜品信息

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);

        List<GoodsSalesDTO> GoodsSales = orderDetailMapper.getTop10Detail(map);
        List<String> namelist = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        for (GoodsSalesDTO detail : GoodsSales) {
            namelist.add(detail.getName());
            numberList.add(detail.getNumber());
        }


        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(namelist, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }


    private Integer getOrderCount(LocalDate begin, LocalDate end, Integer status) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", status);
        Integer OrderCount = orderMapper.countByMap(map);
        return OrderCount == null ? 0 : OrderCount;
    }

    /*导出营业数据报表*/
    @Override
    public void exportBusinessData(HttpServletResponse response) {
//        查询营业数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        ;
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginTime, endTime);

//        通过POi数据写入excel模板中
//              先写入概览数据
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheetAt(0);
            sheet.getRow(1).getCell(1).setCellValue("时间:" + beginTime + "至" + endTime);
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
//            再写入明细数据
            for (int i = 0; i <30 ; i++) {
                LocalDate date=begin.plusDays(i);
                LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);
//                查询某一天的数据
                BusinessDataVO businessData = workspaceService.getBusinessData(min, max);
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());

            }
//        输出流将excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
